"""
场地
"""
from django.db import transaction
import logging
import json

from src.utils import record, hxIm, wx, dataTool
from common.models import TbMiniappUser, ImChatgroup, TbSite, TbSiteApply, TbOrders
from src.utils.ali import imageOcr

errlog = logging.getLogger("err")


class SiteDirector:
    def __init__(self):
        self.sr = record.SiteRecord()
        self.sar = record.SiteApplyRecord()
        self.ima = hxIm.ImAgent()
        self.ur = record.UserRecord()
        self.pa = wx.PayAgent()
        self.order_r = record.OrderRecord()
        self.im = imageOcr.ImageOcr()

    def get_apply_status(self, **kwargs):
        """
        获取是否重复报名
        """
        user: TbMiniappUser = kwargs.get("user")
        site_id = kwargs.get("site_id")
        phone = user.phone
        return self.sar.exits_record(site_id=site_id, status=1, phone=phone, is_delete=0)

    def add_site(self, **kwargs):
        """
        添加场地
        """
        sports_type = kwargs.get("sports_type")
        game_type = kwargs.get("game_type")
        max_participants = kwargs.get("max_participants")
        site_name = kwargs.get("site_name")
        site_type = kwargs.get("site_type")
        site_num = kwargs.get("site_num")
        game_time = kwargs.get("game_time")
        price = kwargs.get("price")
        pay_price = kwargs.get("pay_price")
        order_num = kwargs.get("order_num")
        pay_way = kwargs.get("pay_way")
        order_status = kwargs.get("order_status")
        cover = kwargs.get("cover")
        order_time = kwargs.get("order_time")
        user: TbMiniappUser = kwargs.get("user")
        # 创建
        with transaction.atomic():
            # 创建讨论组
            chatgroup_info = {
                "groupname": f"{site_name}-讨论组",
                "description": f"{site_name}-讨论组",
                "owner": user.phone,
                "custom": {}
            }
            chatgroup: ImChatgroup = self.ima.create_course_task_chatGroup(**chatgroup_info)
            # 创建场地
            create_info = {
                "sports_type": sports_type,
                "game_type": game_type,
                "max_participants": max_participants,
                "site_name": site_name,
                "site_type": site_type,
                "site_num": site_num,
                "game_time": game_time,
                "price": price,
                "pay_price": pay_price,
                "order_num": order_num,
                "pay_way": pay_way,
                "order_status": order_status,
                "cover": cover,
                "order_time": order_time,
                "chatgroup_id": chatgroup.group_id
            }
            site = self.sr.create_record(**create_info)
            return self.sr.record_obj_serializer(site)

    def get_site(self, **kwargs):
        page = kwargs.get("page")
        size = kwargs.get("size")
        user: TbMiniappUser = kwargs.get("user")
        count, result = self.sr.filter_record_page(page=page, size=size)
        result_list = []
        for site in result:
            apply_person = self.sar.filter_record(site_id=site.get("uid"), status=1, is_delete=0)
            site["apply_person"] = apply_person
            result_list.append(site)
            # 场地报名情况
            if user is not None:
                apply_status = self.get_apply_status(site_id=site.get("uid"), user=user)
                site["apply_status"] = apply_status
            else:
                site["apply_status"] = "none"
            for person in apply_person:
                apply_user: TbMiniappUser = self.ur.get_record_condition(phone=person.get("phone"))
                person["profile"] = apply_user.profile
        return (count, result_list)

    def get_site_detail(self, **kwargs):
        """
        场地详情
        """
        site_id = kwargs.get("game_id")
        return self.sr.get_record_detail(site_id)

    def get_apply_info(self, **kwargs):
        """
        获取自己的申请信息
        """
        apply_id = kwargs.get("apply_id")
        apply: TbSiteApply = self.sar.get_record(apply_id)
        return self.sar.record_obj_serializer(apply)

    def site_apply(self, **kwargs):
        """
        场地报名
        """
        site_id = kwargs.get("site_id")
        name = kwargs.get("name")
        phone = kwargs.get("phone")
        address = kwargs.get("address")
        user: TbMiniappUser = kwargs.get("user")
        # 验证
        # --- start ---
        # 验证该赛事是否报名过
        is_exits = self.sar.exits_record(site_id=site_id, status=1, phone=phone, is_delete=0)
        if is_exits:
            raise ValueError("已经报名过了")
        # --- end ---
        with transaction.atomic():
            site: TbSite = self.sr.get_record(site_id)
            apply_info = {
                "site_id": site.uid,
                "name": name,
                "phone": phone,
                "address": address,
                "need_pay": 1,
                "is_payed": 0,
                "status": 0
            }
            site_apply = self.sar.create_record(**apply_info)
            # 加入讨论组
            username = user.username
            group_id = site.chatgroup_id
            join_result = self.ima.join_chatGroup(username=username, group_id=group_id)
            errlog.info(json.dumps(join_result))
            # 保存用户名
            user.name = name
            user.save()
            return self.sar.record_obj_serializer(site_apply)

    def pay_apply_price(self, **kwargs):
        """
        支付报名费用
        """
        site_id = kwargs.get("site_id")
        apply_id = kwargs.get("apply_id")
        user: TbMiniappUser = kwargs.get("user")
        with transaction.atomic():
            site: TbSite = self.sr.get_record(site_id)
            out_trade_no = self.pa.order_num()  # 订单号
            time_expire = dataTool.DateTimeTool().get_after_half_hour()
            time_expire_str = dataTool.DateTimeTool(datetime_obj=time_expire).get_rfc_datetime_str()
            description = "师资保证金缴纳"
            currency = "CNY"
            price = site.pay_price
            attach = json.dumps({
                "apply_id": apply_id
            })
            # 保存订单
            order_info = {
                "total_price": price,
                "pay_price": 0,
                "time_expire": time_expire_str,
                "out_trade_no": out_trade_no,
                "description": description,
                "attach": attach,
                "currency": currency,
                "pay_status": 0,
                "payer_id": user.uid,
                "symbol": "-",
            }
            self.order_r.create_record(**order_info)
            # 支付
            pay_info = {
                "description": description,
                "out_trade_no": out_trade_no,
                "notify_url": "/teacher/securityDepositPaySucess",
                "amount": int(price * 100),
                "openid": user.mini_openid,
                "time_expire": time_expire_str,
                "currency": currency,
                "attach": attach
            }
            result = self.pa.pay(**pay_info)
            result["out_trade_no"] = out_trade_no
            return result

    def apply_pay_success(self, **kwargs):
        """
        报名支付成功
        """
        out_trade_no = kwargs.get("out_trade_no")
        order: TbOrders = self.order_r.get_record_condition(out_trade_no=out_trade_no)
        attach = json.loads(order.attach)
        apply_id = attach.get("apply_id")
        apply: TbSiteApply = self.sar.get_record(apply_id)
        with transaction.atomic():
            # 订单记录
            order.pay_price = 0
            order.pay_status = 1
            order.pay_price = order.total_price
            order.save()
            # 支付成功记录
            apply.is_payed = 1
            apply.status = 1
            apply.out_trade_no = order.out_trade_no
            apply.save()
            result = self.sar.record_obj_serializer(apply)
            return result

    def refund(self, **kwargs):
        """
        退款
        """
        apply_id = kwargs.get("apply_id")
        with transaction.atomic():
            apply: TbSiteApply = self.sar.get_record(apply_id)
            out_trade_no = apply.out_trade_no
            reason = "场地退款"  # 退款理由
            order: TbOrders = self.order_r.get_record_condition(out_trade_no=out_trade_no)
            refund_info = {
                "out_trade_no": out_trade_no,
                "reason": reason,
                "total": int(order.pay_price * 100),
                "refund": int(order.pay_price * 100),
            }
            result = self.pa.refund(**refund_info)
            # 修改状态
            apply.status = 2
            apply.save()
            return result
        # total = kwargs.get("total")  # 订单总金额
        # refund = kwargs.get("refund")  # 退款金额

    def get_my_apply_list(self, **kwargs):
        """
        获取我的申请列表
        """
        user: TbMiniappUser = kwargs.get("user")
        page = kwargs.get("page")
        size = kwargs.get("size")
        return self.sar.filter_record_page(page=page, size=size, phone=user.phone)

    def ocr(self, **kwargs):
        """
        图像识别
        """
        url = kwargs.get("url")
        result = self.im.ocr(url=url)
        return result
